import json
import threading
import time

import requests
from django.http import HttpResponse
from django.shortcuts import render

from DarlingTestTools.settings import logger
from DataCheckAutomatic.test import checkQuotationModule
from DataFactory.common import mysql_conn


# Create your views here.
def check(request, source):
    if source.lower() == "dashboard":
        return render(request,
                      './html/dashboard.html',
                      {'orderType': source}
                      )


class CheckThread (threading.Thread):
    result: object

    def __init__(self, func, env, host, countryID, token_needed):
        threading.Thread.__init__(self)
        self.func = func
        self.env = env
        self.host = host
        self.countryID = countryID
        self.token_needed = token_needed

    def run(self):
        self.result = self.func(self.env, self.host, self.countryID, self.token_needed)

    def get_result(self):
        try:
            return self.result
        except Exception as e:
            print(e)
            return None


class StartCheck:

    def __init__(self):

        self.logger = logger
        self.session = requests.session()
        self.header = {
            "Content-Type": "application/json",
            "countryId": 1001
        }

    def check_daily_kpi(self, env, host, token_needed):
        global cur, conn
        self.logger.info("Start to check Dashboard-DailyKPI.")
        self.logger.info("Start to check Dashboard-DailyKPI with CA/CS list.")
        quoted_data = {}
        print(quoted_data)
        print(env)
        self.header["token"] = token_needed
        quoted_result = self.session.post(
            url=host + "/platform/tms/eggSearchReceiving/map/messengerList/information",
            headers=self.header,
            data=None
        )

        if quoted_result.status_code != 200 and "200" != json.loads(quoted_result.content)['code']:
            self.logger.error("Can not get CS/CA list, please check service!")
            return None
        elif "200" != json.loads(quoted_result.content)['code']:
            self.logger.error("Can not get CS/CA list.")
            return None
        elif not json.loads(quoted_result.content)['data']:
            self.logger.error("Can not get CS/CA list.")
            return None
        else:
            self.logger.info("Get CS/CA list success !\nStart check CA/CS data:\n")
            csca_list = json.loads(quoted_result.content)['data']
            self.logger.info("Checking CA/CS count :")
            self.logger.info("CA/CS count from interface is: " + str(len(csca_list)))
            sql = '''SELECT
                COUNT( * ) 
            FROM
                erp.erp_staff_info aa
                LEFT JOIN erp.admin_user bb ON aa.userId = bb.userId 
            WHERE
                aa.countryId = 1001 
                AND aa.position IN ( "CA", "CS" ) 
                AND bb.userStatus = 1 
                AND aa.`status` = 1 
                AND bb.`status` = 1;'''
            if host == "http://erp.test.jimuitech.com":
                conn = mysql_conn.get_cur(environment="test")["conn"]
                cur = mysql_conn.get_cur(environment="test")["cur"]
            elif host == "http://erp.uat.jimuitech.com":
                conn = mysql_conn.get_cur(environment="UAT")["conn"]
                cur = mysql_conn.get_cur(environment="UAT")["cur"]
            elif host == "http://erp.stable.jimuitech.com":
                conn = mysql_conn.get_cur(environment="stable")["conn"]
                cur = mysql_conn.get_cur(environment="stable")["cur"]
            cur.execute(sql)
            data = cur.fetchall()
            if len(data) == 0:
                logger.error("Can not get CA/CA data from MySQL.")
            else:
                logger.info("Quotation No. is : " + str(data[0][1]))
            conn.commit()


def check_dashboard(request):
    global host_url, customer_id, orders, thread, country_id
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.POST:
            source_type = request.POST.get('sourceType', 0)
            host = request.POST.get('environment', 0)
            country = request.POST.get("country")
            thread_count = request.POST.get('threadCount', 0)

            if host == "Test":
                host_url = "http://erp.test.jimuitech.com"
            elif host == "UAT":
                host_url = "http://erp.uat.jimuitech.com"
            elif host == "Stable":
                host_url = "http://erp.stable.jimuitech.com"

            if country == "Thailand":
                country_id = 1001
            elif country == "Indonesia":
                country_id = 1102

            session = requests.session()
            login_data = {
                "username": "kap1chn",
                "password": "1234qwer",
                "loginSource": "ERP"
            }
            login_result = session.post(url=host_url + "/platform/admin/auth/login",
                                        data=json.dumps(login_data),
                                        headers={
                                            "Content-Type": "application/json"
                                        }
                                        ).content
            token_needed = json.loads(login_result)["data"]["token"]

            order_final = []
            threads = []
            for i in range(1, int(thread_count) + 1):
                if source_type == 'daily_kpi' or source_type == 'SellOrder' or source_type == 'sellOrder' or source_type == 'Sellorder':
                    thread = CheckThread(func=StartCheck.check_daily_kpi, env=host, host=host_url, countryID=country_id, token_needed=token_needed)
                elif source_type == 'quotation' or source_type == 'Quotation':
                    thread = CheckThread(func=checkQuotationModule.CheckDashboardQuotation.check_all_chat_quotation_not_answered_after_30_minutes, env=host, host=host_url, countryID=country_id, token_needed=token_needed)
                elif source_type == 'all' or source_type == 'ALL' or source_type == 'All':
                    pass
                    # thread = CheckThread(func=)
                thread.start()
                threads.append(thread)
                time.sleep(0.3)
            for t in threads:
                t.join()
                order_final.append(t.get_result())
            return HttpResponse(json.dumps(order_final, ensure_ascii=False), content_type="application/json,charset=utf-8")
        else:
            return HttpResponse('输入为空')

    else:
        return HttpResponse('方法错误')
